package com.cskaoyan.order.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.bean.Member;
import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.order.biz.Bean.CancelOrderBO;
import com.cskaoyan.order.biz.Bean.CommonBO;
import com.cskaoyan.order.biz.Bean.ShoppingOrderVO;
import com.cskaoyan.order.dto.OrderDetailResponse;
import com.cskaoyan.order.form.CreateOrderRequest;
import com.cskaoyan.order.service.OrderCoreService;
import com.cskaoyan.order.service.OrderQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @author wxgl
 * @date 2023-01-09 21:43
 * @describe
 */
@RestController
@RequestMapping("shopping")
public class OrderController {
    @Autowired
    @Qualifier("orderCoreServiceImpl1")
    OrderCoreService orderCoreService;

    @Autowired
    @Qualifier("orderQueryServiceImpl1")
    OrderQueryService orderQueryService;

    /**
     * @Author xiaowu
     * @Description //创建订单
     * @Date 11:31 2023/1/10
     * @Param [request, servletRequest]
     * @return com.cskaoyan.mall.commons.result.ResponseData
     **/
    @PostMapping("order")
    public ResponseData shoppingOrder(@RequestBody CreateOrderRequest request, HttpServletRequest servletRequest){
        //问一下登录的人，token里面放的是什么key
        //从request域中获取用户信息
//        String userInfo = (String)servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
//        JSONObject object = JSON.parseObject(userInfo);
//        long uid = Long.parseLong(object.get("uid").toString());
        Cookie[] cookies = servletRequest.getCookies();
        String value = null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("access_token")){
                value = cookie.getValue();
            }
        }
        JwtTokenUtils build = JwtTokenUtils.builder().token(value).build();
        String s = build.freeJwt();
        Member member = JSON.parseObject(s, Member.class);
        Long uid = member.getId();
        request.setUserId(uid);

        //设置UniqueKey
        request.setUniqueKey(UUID.randomUUID().toString());

        String orderId = orderCoreService.createOrder(request);
        if (orderId == null){
            return new ResponseUtil<>().setErrorMsg(SysRetCodeConstants.DB_EXCEPTION.getMessage());
        }
        return new ResponseUtil<>().setData(orderId);
    }

    /**
     * @Author xiaowu
     * @Description //產看所有訂單
     * @Date 0:40 2023/1/10
     * @Param size=5&page=1
     * @return  {"success":true,"message":null,"code":200,"result":{"data":[{"orderId":"23010923481209322","payment":8997.00,"paymentType":null,"postFee":null,"status":5,"createTime":"2023-01-09 23:48:12","updateTime":"2023-01-09 23:48:12","paymentTime":null,"consignTime":null,"endTime":null,"closeTime":null,"shippingName":null,"shippingCode":null,"userId":74,"buyerMessage":null,"buyerNick":null,"buyerComment":null,"orderItemDto":[{"id":"23010923481210225","itemId":"100046401","orderId":"23010923481209322","num":3,"title":"坚果 R1","price":2999.0,"totalFee":8997.0,"picPath":"https://resource.smartisan.com/resource/06c2253354096f5e9ebf0616f1af2086.png"},{"id":"23010923481211118","itemId":"100053202","orderId":"23010923481209322","num":0,"title":"地平线 8 号商务旅行箱","price":999.0,"totalFee":0.0,"picPath":"https://resource.smartisan.com/resource/d1dcca9144e8d13ffb33026148599d0a.png"}],"orderShippingDto":{"orderId":"23010923481209322","receiverName":"狗蛋","receiverPhone":"13488889999","receiverMobile":null,"receiverState":null,"receiverCity":null,"receiverDistrict":null,"receiverAddress":"河北省-石家庄市-市辖区-哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈","receiverZip":null}},{"orderId":"23010923463900618","payment":79.00,"paymentType":null,"postFee":null,"status":5,"createTime":"2023-01-09 23:46:39","updateTime":"2023-01-09 23:46:39","paymentTime":null,"consignTime":null,"endTime":null,"closeTime":null,"shippingName":null,"shippingCode":null,"userId":74,"buyerMessage":null,"buyerNick":null,"buyerComment":null,"orderItemDto":[{"id":"23010923463902017","itemId":"100023501","orderId":"23010923463900618","num":1,"title":"Smartisan 双口 & 快充车载充电器","price":79.0,"totalFee":79.0,"picPath":"https://resource.smartisan.com/resource/d4480234a2f24b0ff5acd98288fd902d.jpg"}],"orderShippingDto":{"orderId":"23010923463900618","receiverName":"软件新城","receiverPhone":"13222222222","receiverMobile":null,"receiverState":null,"receiverCity":null,"receiverDistrict":null,"receiverAddress":"内蒙古自治区-呼和浩特市-新城区-21-2101","receiverZip":null}},{"orderId":"23010923310559831","payment":149.00,"paymentType":null,"postFee":null,"status":7,"createTime":"2023-01-09 23:31:06","updateTime":"2023-01-09 23:31:06","paymentTime":null,"consignTime":null,"endTime":null,"closeTime":"2023-01-09 23:32:31","shippingName":null,"shippingCode":null,"userId":74,"buyerMessage":null,"buyerNick":null,"buyerComment":null,"orderItemDto":[{"id":"23010923310560822","itemId":"100057501","orderId":"23010923310559831","num":1,"title":"Smartisan T恤 毕加索","price":149.0,"totalFee":149.0,"picPath":"https://resource.smartisan.com/resource/d9586f7c5bb4578e3128de77a13e4d85.png"}],"orderShippingDto":{"orderId":"23010923310559831","receiverName":"软件新城","receiverPhone":"13222222222","receiverMobile":null,"receiverState":null,"receiverCity":null,"receiverDistrict":null,"receiverAddress":"内蒙古自治区-呼和浩特市-新城区-21-2101","receiverZip":null}},{"orderId":"23010922591730589","payment":299.00,"paymentType":null,"postFee":null,"status":5,"createTime":"2023-01-09 22:59:17","updateTime":"2023-01-09 22:59:17","paymentTime":null,"consignTime":null,"endTime":null,"closeTime":null,"shippingName":null,"shippingCode":null,"userId":74,"buyerMessage":null,"buyerNick":null,"buyerComment":null,"orderItemDto":[{"id":"23010922591731645","itemId":"100053312","orderId":"23010922591730589","num":1,"title":"地平线 8 号旅行箱","price":299.0,"totalFee":299.0,"picPath":"https://resource.smartisan.com/resource/db4895e45ee6f3339037dbf7200e63f2.png"}],"orderShippingDto":{"orderId":"23010922591730589","receiverName":"软件新城","receiverPhone":"13222222222","receiverMobile":null,"receiverState":null,"receiverCity":null,"receiverDistrict":null,"receiverAddress":"内蒙古自治区-呼和浩特市-新城区-21-2101","receiverZip":null}},{"orderId":"23010422240857852","payment":123135.00,"paymentType":null,"postFee":null,"status":1,"createTime":"2023-01-04 22:24:09","updateTime":"2023-01-04 22:24:09","paymentTime":null,"consignTime":null,"endTime":null,"closeTime":null,"shippingName":null,"shippingCode":null,"userId":74,"buyerMessage":null,"buyerNick":null,"buyerComment":null,"orderItemDto":[{"id":"23010422240861205","itemId":"100042203","orderId":"23010422240857852","num":3,"title":"坚果“电池形电池”移动电源","price":49.0,"totalFee":147.0,"picPath":"https://resource.smartisan.com/resource/33954b3f6a2f1614c5482ef130af9cc8.jpg"},{"id":"23010422240860318","itemId":"100051701","orderId":"23010422240857852","num":65,"title":"坚果 Pro 2S","price":1798.0,"totalFee":116870.0,"picPath":"https://resource.smartisan.com/resource/b07b9765e272f866da6acda4ee107d88.png"},{"id":"23010422240858734","itemId":"100053312","orderId":"23010422240857852","num":9,"title":"地平线 8 号旅行箱","price":299.0,"totalFee":2691.0,"picPath":"https://resource.smartisan.com/resource/db4895e45ee6f3339037dbf7200e63f2.png"},{"id":"23010422240859499","itemId":"100057601","orderId":"23010422240857852","num":23,"title":"T恤 皇帝的新装","price":149.0,"totalFee":3427.0,"picPath":"https://resource.smartisan.com/resource/d9586f7c5bb4578e3128de77a13e4d85.png"}],"orderShippingDto":{"orderId":"23010422240857852","receiverName":"软件新城","receiverPhone":"13222222222","receiverMobile":null,"receiverState":null,"receiverCity":null,"receiverDistrict":null,"receiverAddress":"内蒙古自治区-呼和浩特市-新城区-21-2101","receiverZip":null}}],"total":233},"timestamp":1673282344016}
     **/
    @GetMapping("order")
    public ResponseData shoppingOrder(CommonBO commonBO,HttpServletRequest servletRequest){
        Cookie[] cookies = servletRequest.getCookies();
        String value = null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("access_token")){
                value = cookie.getValue();
            }
        }
        JwtTokenUtils build = JwtTokenUtils.builder().token(value).build();
        String s = build.freeJwt();
        Member member = JSON.parseObject(s, Member.class);
        Long uid = member.getId();

        ShoppingOrderVO shoppingOrderVO = orderQueryService.shoppingOrder(commonBO,uid);
        return new ResponseUtil<>().setData(shoppingOrderVO);
    }

    /**
     * @Author xiaowu
     * @Description // 查询订单详情
     * @Date 8:52 2023/1/10
     * @Param   http://124.221.21.69:8080/shopping/order/23010922591730589
     * @return   {"success":true,"message":null,"code":200,"result":{"userName":null,"orderTotal":299.00,"userId":74,"goodsList":[{"id":"23010922591731645","itemId":"100053312","orderId":"23010922591730589","num":1,"title":"地平线 8 号旅行箱","price":299.0,"totalFee":299.0,"picPath":"https://resource.smartisan.com/resource/db4895e45ee6f3339037dbf7200e63f2.png"}],"tel":"13222222222","streetName":"内蒙古自治区-呼和浩特市-新城区-21-2101","orderStatus":5},"timestamp":1673311975579}
     **/
    @GetMapping("order/{orderId}")
    public ResponseData shoppingOrder(@PathVariable("orderId") String orderId,HttpServletRequest request){
        String userInfo = request.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = Long.parseLong(object.get("id").toString());
        OrderDetailResponse orderDetailResponse = orderQueryService.orderDetail(orderId,uid);
        return new ResponseUtil<>().setData(orderDetailResponse);
    }

    /**
     * @Author xiaowu
     * @Description //  取消订单
     * @Date 9:59 2023/1/10
     * @Param orderId:"23011009494069978"    http://124.221.21.69:8080/shopping/cancelOrder
     * @return  {"success":true,"message":null,"code":200,"result":null,"timestamp":1673315601053}
     **/
    @PostMapping("cancelOrder")
    public ResponseData cancelOrder(@RequestBody CancelOrderBO cancelOrderBO){
        String orderId = cancelOrderBO.getOrderId();
        orderCoreService.cancelOrder(orderId);
        return new ResponseUtil<>().setData(null);
    }

    /**
     * @Author xiaowu
     * @Description // 删除订单
     * @Date 10:50 2023/1/10
     * @Param   http://124.221.21.69:8080/shopping/order/23010923481209322
     * @return  {"success":true,"message":null,"code":200,"result":null,"timestamp":1673319046589}
     **/
    @DeleteMapping("order/{orderId}")
    public ResponseData daleteOrder(@PathVariable("orderId") String orderId){
        orderCoreService.deleteOrder(orderId);
        return new ResponseUtil<>().setData(null);
    }
}
